//
//  MenuView.m
//  SlashEM
//
//  Created by dirk on 1/5/10.
//  Copyright 2010 Dirk Zimmermann. All rights reserved.
//

//  This file is part of Slash'EM.
//
//  Slash'EM is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, version 2 of the License only.
//
//  Slash'EM is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with Slash'EM.  If not, see <http://www.gnu.org/licenses/>.

#import "MenuView.h"
#import "NhMenuWindow.h"
#import "NhItem.h"
#import "NhItemGroup.h"
#import "UIFactory.h"
#import "ItemCellView.h"
#import "NhEventQueue.h"
#import "NhEvent.h"
#import "ActionBar.h"
#import "ZAction.h"

@implementation MenuView

@synthesize menuWindow;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		myTableView = [[UITableView alloc] initWithFrame:self.contentView.bounds style:UITableViewStyleGrouped];
		myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		myTableView.dataSource = self;
		myTableView.delegate = self;
		[self.contentView addSubview:myTableView];
		[myTableView release];
    }
    return self;
}

- (void)menuCanceled:(id)sender {
	[[NhEventQueue instance] addKey:-1];
	[self removeFromSuperview];
}

- (void)menuOk:(id)sender {
	for (NhItemGroup *g in menuWindow.itemGroups) {
		for (NhItem *i in g.items) {
			if (i.selected) {
				[menuWindow.selected addObject:i];
			}
		}
	}
	[[NhEventQueue instance] addKey:menuWindow.selected.count];
	[self removeFromSuperview];
}

- (void)menuSelectAll:(id)sender {
	static BOOL select = YES;
	for (NhItemGroup *g in menuWindow.itemGroups) {
		for (NhItem *i in g.items) {
			i.selected = select;
		}
	}
	[myTableView reloadData];
	select = !select;
	UIButton *button = (UIButton *) ((ZAction *)sender).sender;
	[button setTitle:select?@" All ":@"None" forState:UIControlStateNormal];
}

- (void)setMenuWindow:(NhMenuWindow *)w {
	if (w != menuWindow) {
		[menuWindow release];
		menuWindow = [w retain];
		[myTableView reloadData];
		NSMutableArray *commands = [NSMutableArray array];
		[commands addObject:[ZAction actionWithTitle:@"Cancel" target:self action:@selector(menuCanceled:)]];
		if (w.how == PICK_ANY) {
			[commands addObject:[ZAction actionWithTitle:@" All " target:self action:@selector(menuSelectAll:)]];
			[commands addObject:[ZAction actionWithTitle:@"Ok" target:self action:@selector(menuOk:)]];
		}
		self.actionBar.actions = commands;
	}
}

// awkward and slow, but seems to be the only way to resize cells on rotation
- (void)layoutSubviews {
	[super layoutSubviews];
	[myTableView reloadData];
}

- (void)dealloc {
	[menuWindow release];
    [super dealloc];
}

#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return menuWindow.itemGroups.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NhItemGroup *g = [menuWindow.itemGroups objectAtIndex:section];
	return g.title;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NhItemGroup *g = [menuWindow.itemGroups objectAtIndex:section];
	return g.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static int kCellViewTag = 1;
	static NSString *cellId = @"menuViewControllerCellId";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
	if (!cell) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellId] autorelease];
		cell.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		ItemCellView *cellView = [[ItemCellView alloc] initWithFrame:cell.bounds];
		cellView.menuWindow = menuWindow;
		cellView.tag = kCellViewTag;
		[cell.contentView addSubview:cellView];
		[cellView release];
	}
	int section = [indexPath section];
	int row = [indexPath row];
	NhItem *item = [menuWindow itemAt:row inGroup:section];
	cell.accessoryType = item.selected ? UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
	ItemCellView *cellView = (ItemCellView *) [cell.contentView viewWithTag:kCellViewTag];
	cellView.item = item;
	return cell;
}

#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	int section = [indexPath section];
	int row = [indexPath row];
	NhItem *item = [menuWindow itemAt:row inGroup:section];
	//NSLog(@"selected %d,%d %@", section, row, item.title);
	if (menuWindow.how == PICK_ONE) {
		if (item.maxAmount == -1 || item.amount != -1) {
			// no amount possible, or amount already chosen (subsequent click)
			[menuWindow.selected addObject:item];
			[menuWindow.selected addObject:item];
			[[NhEventQueue instance] addKey:1];
			[self removeFromSuperview];
		} else {
			if (lastIndexPathClicked) {
				int oldSection = [lastIndexPathClicked section];
				int oldRow = [lastIndexPathClicked row];
				NhItem *oldItem = [menuWindow itemAt:oldRow inGroup:oldSection];
				oldItem.amount = -1;
				[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:lastIndexPathClicked] withRowAnimation:NO];
			}
			item.amount = item.maxAmount;
			[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:NO];
			lastIndexPathClicked = indexPath;
		}
	} else if (menuWindow.how == PICK_ANY) {
		UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
		if (item.maxAmount == -1) {
			// just toggle if there is no amount possible
			item.selected = !item.selected;
		} else {
			item.selected = !item.selected;
			if (item.selected) {
				item.amount = item.maxAmount;
			} else {
				item.amount = -1;
			}
			[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:NO];
		}
		cell.accessoryType = item.selected ? UITableViewCellAccessoryCheckmark:UITableViewCellAccessoryNone;
	}
}

@end
